/*
 * Copyright (C) 2013 Daniel Wasilew <daniel.wasilew@codeminer.org>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package org.codeminer.parts.server;

import com.sun.jersey.api.container.grizzly2.GrizzlyServerFactory;
import com.sun.jersey.api.core.ApplicationAdapter;
import com.sun.jersey.api.core.ResourceConfig;
import com.sun.jersey.api.json.JSONConfiguration;
import org.codeminer.parts.application.ApplicationComponent;
import org.codeminer.parts.application.ApplicationContext;
import org.codeminer.parts.application.ShutdownCallback;
import org.codeminer.parts.settings.Settings;
import org.glassfish.grizzly.http.server.HttpServer;
import org.glassfish.grizzly.http.server.StaticHttpHandler;

import javax.ws.rs.core.UriBuilder;
import java.net.URI;

/**
 * User: Daniel Wasilew <daniel.wasilew@codeminer.org>
 * Date: 31.12.12
 * Time: 14:51
 */
public class RestServer implements ApplicationComponent {
    private HttpServer httpServer;

    @Override
    public void startup(ApplicationContext context, ShutdownCallback shutdownCallback) throws Exception {
        Settings settings = context.getApplicationPart(Settings.class);
        URI baseUrl = UriBuilder.fromUri("http://0.0.0.0/").port(settings.getWebAccessPort()).build();
        ResourceConfig rc = new ApplicationAdapter(context.getApplicationPart(DefaultWebApplication.class));
        rc.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE);


        httpServer = GrizzlyServerFactory.createHttpServer(baseUrl, rc);

        httpServer.getServerConfiguration().addHttpHandler(new StaticHttpHandler(context.getHelpDir().getAbsolutePath()), "/help");
        httpServer.start();
    }

    @Override
    public void shutdown() {
        httpServer.stop();
    }

    @Override
    public Class getDescriptionClass() {
        return RestServer.class;
    }

}
